package sys;

import java.util.*;
import java.io.*;
import java.sql.*;
import java.util.concurrent.*;

import sys.fsm.*;
import sys.transport.*;
import sys.logic.*;
import sys.message.*;
import sys.database.*;
import org.json.*;
import sys.utils.*;

public class RequestManager
{
    public RequestManager(String confFilePath)
    {
        readParams(confFilePath);

        ms = new MessageSenderSMTP(mailserver, portSMTP);

        db = new DBWrapper(DBServer, DB, DBUser, DBPass);
        db.connect();
       
        try { nextID = SyscDatabase.maxRequestID(DBServer, DB, DBUser, DBPass) + 1; }
        catch(Exception e) { System.out.println("Error when retrieving MAX(ID) : " + e.getMessage()); }
        requests = new Hashtable<Integer, Automat>();
    }

    private void readParams(String confFilePath)
    {
        File confFile = new File(confFilePath);
        String conf = ReadWriteTextFile.getContents(confFile);

        try
        {
            JSONObject jo = new JSONObject(conf);

            mailserver = jo.getString("mailserver");
            portSMTP = jo.getString("smtpport");
            portPOP3 = jo.getString("pop3port");
            maillogin = jo.getString("maillogin");
            mailpass = jo.getString("mailpass");

            DBServer = jo.getString("DBServer");
            DB = jo.getString("DB");
            DBUser = jo.getString("DBUser");
            DBPass = jo.getString("DBPass");

            mailboxCheckingInterval = jo.getInt("mailboxCheckingInterval");
        }
        catch(JSONException e)
        {
            System.out.println("Receiver : Error while parsing config file : " + e.getMessage());
        }

    }

    public void start()
    {
        MessageReceiver mr = new MessageReceiverPOP3(mailserver, portPOP3, maillogin, mailpass);
        MessageCheckerClient mcc = new MailsEntryPoint();
        mc = new MessageChecker(mr, mcc, mailboxCheckingInterval);
        mc.start();
    }

    public void stop()
    {
        mc.stop();
    }

    class MailsEntryPoint implements MessageCheckerClient
    {
        public void newMessages(ConcurrentLinkedQueue<UniMessage> messages)
        {
            System.out.println("Systemc have got a message");
            for (UniMessage m : messages)
            {
                System.out.println("FROM: " + m.getFrom() + ", TO: " + m.getTo() + ", BODY: " + m.getBody());
            
                String type = null;
                try
                {
                    type = m.getString("Type");
                }
                catch(JSONException e)
                {
                    System.out.println("Error when retrieving field 'Type' : " + e.getMessage());
                    continue;
                }

                if (type.compareTo("newRequest") == 0)
                {
                    System.out.println("New request");
                    try
                    {
                        int askAboutId = m.getInt("ID");

                        db.insert("Request", "ID, IDOnBuyer, Buyer_Address", nextID + "," + askAboutId + ",'" +m.getFrom() +"'");
                        nextID++;
                    }
                    catch(Exception e) {System.out.println("Error when retiriving fields from 'NewRequest': " + e.getMessage());};
                }
                else if (type.compareTo("payingStatus") == 0)
                {
                    System.out.println(m.getFrom() + " is asking about paying status of request");

                    try
                    {
                        int askAboutId = m.getInt("AskAboutID");
                        int Id = m.getInt("ID");

                        ResultSet rs = db.select("Request", "IDOnBuyer = " + askAboutId);
                        if (rs.next())
                        {
                            JSONMessage mes = new JSONMessage(maillogin+"@"+mailserver, m.getFrom(), "Ack from paying system");
                            mes.put("Type", "ackPayingSystem");
                            mes.put("ackOn", Id);
                            ms.send(mes);
                        }
                        else
                        {
                            System.out.println("There is not request number " + askAboutId + " in the database");
                        }

                    }
                    catch(Exception e) {System.out.println("Error when retiriving fields from 'payingStatus' and sending a message: " + e.getMessage());};
                }
                else
                {
                    System.out.println("Unknown type. Skipping.");
                }
            }
        }
    }

    // Parametrs
    private String mailserver, maillogin, mailpass, portSMTP, portPOP3;
    private String DBServer, DB, DBUser, DBPass;
    long mailboxCheckingInterval;

    private DBWrapper db;
    private MessageSender ms;

    MessageChecker mc;
    private Hashtable<Integer, Automat> requests;
    private int nextID;
}
